package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @作者 itcast
 * @创建日期 2021/4/5 15:23
 **/
//@Component
//@Order(1)
public class LoginFilter implements GlobalFilter, Ordered {
    /**
     * @param exchange : 封装了 请求对象  和  响应对象
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取 请求对象 和 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2. 根据请求对象获取请求头(access-token)信息
        HttpHeaders headers = request.getHeaders();
        String accessToken = headers.getFirst("access-token");
        // 3. 判断access-token是否等于admin
        if("admin".equals(accessToken)){
            // 4. 等于   放行这个请求
            return chain.filter(exchange);// 放行请求
        }else {
            // 5. 不等于   终止请求 并且设置响应码为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 终止响应
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
